//
//  QSAppTool.swift
//  TestSwift
//
//  Created by Song on 2018/5/7.
//  Copyright © 2018 Song. All rights reserved.
//

import UIKit

class QSAppTool: NSObject {
    /// 通过字符串创建class
    ///
    /// - Parameters:
    ///   - className: class名
    ///   - classType: class类型
    /// - Returns: class
    class func qs_createClass(_ className: String) -> AnyClass {
        // 获取命名空间
        guard let clasName = Bundle.main.infoDictionary!["CFBundleExecutable"] else {
            fatalError("命名空间不存在")
        }
        
        // 通过命名空间和类名转换成类
        guard let cls = NSClassFromString(clasName as! String + "." + className) else {
            fatalError("无法转换成相应类型")
        }
        
        return cls
    }
    
    /**
     *  截屏
     */
    static func qs_screenShot() -> UIImage {
        let imageSize = UIScreen.main.bounds.size
        
        UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
        UIGraphicsBeginImageContext(imageSize)
        
        let context = UIGraphicsGetCurrentContext()
        for window in UIApplication.shared.windows {
            if window.responds(to: #selector(getter: window.screen)) || window.screen == UIScreen.main {
                context!.saveGState()
                context!.translateBy(x: window.center.x, y: window.center.y)
                context!.concatenate(window.transform)
                context!.translateBy(x: -window.bounds.size.width * window.layer.anchorPoint.x, y: -window.bounds.size.height * window.layer.anchorPoint.y)
                window.layer.render(in: context!)
                
                context!.restoreGState()
            }
        }
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image!
    }
    
    /**
     *  截屏，根据给定的view
     */
    class func qs_screenShot(_ view: UIView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0.0)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    /// 异步获取图片尺寸
    ///
    /// - Parameter imgUrl: 图片url字符串
    class func qs_getImageSize(_ imgUrl: String, success: @escaping ((CGSize) -> ())) {
        DispatchQueue.global(qos: .default).async {
            var urlStr = imgUrl
            if imgUrl.hasPrefix("http://") || imgUrl.hasPrefix("https://") {
            } else {
                urlStr = Host + urlStr
            }
            
            if let url = URL.init(string: urlStr) {
                let data = try? Data.init(contentsOf: url)
                if data != nil {
                    if let image = UIImage.init(data: data!) {
                        success(image.size)
                        return
                    }
                }
            }
            
            success(CGSize.zero)
        }
    }
}
